﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ShareMarking.Systems.Service;
using ShareMarking.Service;
using ShareMarking.Entity;
using System.Data;
using Common.Utilities.Excel.Export;
using Common.Utilities.Excel;
using MySoft.Data;
using System.IO;
using ShareMarking.Interface;
using System.Net;
using System.Drawing.Imaging;

namespace ShareMarking.Web.admin.EnterPrise.Employee
{
    public partial class NC : ManagePage
    {
        #region 参数配置=================================

        protected int totalCount;
        protected int page;
        protected string pageSizeCookieKey = "nc_ncuser_index_page_size";//当前页的每页大小的cookiekey
        protected string nc_code = string.Empty;
        protected string nc_name = string.Empty;
        protected string nc_phone = string.Empty;
        protected string state = string.Empty;
        protected int pageSize {
            get
            {
                int _default_size = 10;
                int _pagesize;
                if (int.TryParse(Utils.GetCookie(pageSizeCookieKey), out _pagesize))
                {
                    if (_pagesize > 0)
                    {
                        return _pagesize;
                    }
                }
                return _default_size;
            }
        }
        protected string orderBy = "nc_ncuser.id desc";

        protected string keywords = string.Empty;
        protected string searchURL { get { return Utils.CombUrlTxt("NC.aspx", "nc_code={0}&nc_name={1}&nc_phone={2}&state={3}", this.nc_code, this.nc_name, this.nc_phone, this.state); } }

        #endregion

        #region 初始化===================================

        protected void Page_Load(object sender, EventArgs e)
        {
            //检查权限
            //ChkAdminLevel("user_list", ShareMarkingEnums.ActionEnum.View.ToString());

            //初始化搜索参数
            this.keywords = DTRequest.GetQueryString("keywords");
            this.nc_code = DTRequest.GetQueryString("nc_code");
            this.nc_name = DTRequest.GetQueryString("nc_name");//"B298E746A95B76444878F8ECF9921125";
            this.nc_phone = DTRequest.GetQueryString("nc_phone");//"062ED0481E10985C";
            this.state = DTRequest.GetQueryString("state");
            if (!Page.IsPostBack)
            {
                //绑定下拉框的值

                //绑定列表
                RptBind();
            }
        }

        #endregion

        #region 绑定下拉框===============================

        #endregion

        #region 下拉框改变事件===========================
        protected void ddlISdraw_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.state = this.ddlISdraw.SelectedValue.ToLower();
            this.nc_code = txtnc_code.Text;
            this.nc_name = txtname.Text;
            this.nc_phone = txtphone.Text;
            Response.Redirect(searchURL);
        }
        #endregion

        #region 绑定列表=================================
        private void RptBind()
        {
            this.page = DTRequest.GetQueryInt("page", 1);
            
            //获取数据源            
            if (!nc_code.IsNullOrEmpty())
            {
                this.txtnc_code.Text = nc_code;
            } 
            if (!nc_name.IsNullOrEmpty())
            {
                this.txtname.Text = nc_name;
            } 
            if (!nc_phone.IsNullOrEmpty())
            {
                this.txtphone.Text = nc_phone;
            }
            if (!state.IsNullOrEmpty())
            {
                if (state == "true" || state == "false")
                {
                    this.ddlISdraw.SelectedValue = state;
                }
                if (state == "所有")
                {
                    state = "";
                    this.ddlISdraw.SelectedValue = "所有";
                }                      
            }
            else 
            {
                state = "true";
            }
            this.rptList.DataSource = nc_ncuserService.Instance.Get_nc_ncuser_PageSelect(page, pageSize, orderBy, out totalCount, nc_code, nc_name, nc_phone, state);
            this.rptList.DataBind();

            //绑定页码
            txtPageNum.Text = this.pageSize.ToString();
            string pageUrl = ComLib.UrlHelper.Instance.SetUrl(searchURL).AddParam("page", "__id__").GetAddedParamUrl();
            PageContent.InnerHtml = Utils.OutPageList(this.pageSize, this.page, this.totalCount, pageUrl, 8);
        }
        #endregion

        #region 搜索操作=================================

        //关健字查询
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            this.keywords = txtKeywords.Text;
            Response.Redirect(searchURL);
        }

        //关健字查询
        protected void btnDetailedSearch_Click(object sender, EventArgs e)
        {
            //this.keywords = txtKeywords.Text;
            this.nc_code = txtnc_code.Text;
            this.nc_name = txtname.Text;
            this.nc_phone = txtphone.Text;
            this.state = ddlISdraw.SelectedValue;
            Response.Redirect(searchURL);
        }

        //筛选类别
        //设置分页数量
        protected void txtPageNum_TextChanged(object sender, EventArgs e)
        {
            int _pagesize;
            if (int.TryParse(txtPageNum.Text.Trim(), out _pagesize))
            {
                if (_pagesize > 0)
                {
                    Utils.WriteCookie(pageSizeCookieKey, _pagesize.ToString(), 14400);
                }
            }
            Response.Redirect(searchURL);
        }

        #endregion

        #region 删除操作=================================

        //批量删除
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            //检查权限
            ChkAdminLevel("user_list", DTEnums.ActionEnum.Delete.ToString());

            int sucCount = 0;
            int errorCount = 0;
            for (int i = 0; i < rptList.Items.Count; i++)
            {
                int id = Convert.ToInt32(((HiddenField)rptList.Items[i].FindControl("hidId")).Value);
                CheckBox cb = (CheckBox)rptList.Items[i].FindControl("chkId");
                if (cb.Checked)
                {
                    if (nc_ncuserService.Instance.Delete_Entity(ShareMarking.Entity.nc_ncuser._.id == id))
                    {
                        sucCount += 1;
                    }
                    else
                    {
                        errorCount += 1;
                    }
                }
            }

            //记录日志
            AddAdminLog(DTEnums.ActionEnum.Delete.ToString(), "删除nc_ncuser" + sucCount + "条，失败" + errorCount + "条");

            JscriptMsg("删除成功" + sucCount + "条，失败" + errorCount + "条！", searchURL, "Success");
        }

        #endregion

        #region 生成二维码
        public string geturl(string nccode)
        {
            var rela = qr_QrCodeRelateService.Instance.Get_SingleEntity_byWhere(
                qr_QrCodeRelate._.IsDelete == false &&
                qr_QrCodeRelate._.qr_Type == 1 && qr_QrCodeRelate._.rel_Code == nccode);
            if (rela != null)
            {
                var qrcode = qr_QrCodeService.Instance.Get_SingleEntity_byWhere(qr_QrCode._.scene_id == rela.qr_Scene_ID);
                if (qrcode != null)
                    return qrcode.qrcode_url;
                return "";
            }
            return "";
        }
        #endregion

        #region 导出成Excel表格==================

        protected void btnDownload_Click(object sender, EventArgs e)
        {
            int sucCount = 0;
            int errorCount = 0;
            try
            {
                DataSet ds = new DataSet();
                DataTable table = new DataTable();
                string sql = @"select nc.nc_code,nc.name,nc.tel,nc.email,nc.state,nc.nc_nature,nc.entr_date,nc.leave_date,qr.qrcode_url from nc_ncuser nc left join qr_QrCodeRelate rel on nc.nc_code=rel.rel_Code left join qr_QrCode qr on rel.qr_Scene_ID=qr.scene_id where rel.IsDelete=0";
                table = DbSession.Default.FromSql(sql).ToTable();
                
                table.TableName = "nc_ncuser";
                ds.Tables.Add(table);

                ExcelUtilities excelUtils = new ExcelUtilities();
                excelUtils.ExportExcel(Response, string.Format("ExportCode_{0}", DateTime.Now.ToString("yyyy-MM-dd")), ds, "ncinfo");
                sucCount += 1;
            }
            catch (Exception ex)
            {
                WriteLog.WriteError(ex.ToString());
                JscriptMsg("下载时发生错误请联系管理员！", searchURL, "Error");
            }
            //记录日志
            AddAdminLog(DTEnums.ActionEnum.Export.ToString(), "导出NC用户信息" + sucCount + "条，失败" + errorCount + "条");

            JscriptMsg("下载成功" + sucCount + "条，失败" + errorCount + "条！", searchURL, "Success");
        }

        protected void btnDownload_Click2(object sender, EventArgs e)
        {
            int sucCount = 0;
            int errorCount = 0;
            try
            {
                DataSet ds = new DataSet();
                DataTable table = new DataTable();
                string sql = @"SELECT top 20 1 AS qrtype, nc.nc_code,qr.scene_id,qr.qrcode_url,qr.code_url,'55' AS httpcontent 
from nc_ncuser nc left join qr_QrCodeRelate rel on nc.nc_code=rel.rel_Code 
left join qr_QrCode qr on rel.qr_Scene_ID=qr.scene_id where rel.IsDelete=0";

                table = DbSession.Default.FromSql(sql).ToTable();
                table.TableName = "checktb";

                CheckQrcode check = new CheckQrcode();
                for (int i = 0; i < table.Rows.Count; i++)
                {
                    var imgurl = table.Rows[i]["qrcode_url"].ToString();
                    table.Rows[i]["httpcontent"] = check.getqrcontent(imgurl);
                }

                ds.Tables.Add(table);

                ExcelUtilities excelUtils = new ExcelUtilities();
                excelUtils.ExportExcel(Response, string.Format("检查结果导出_{0}", DateTime.Now.ToString("yyyy-MM-dd")), ds, "checkinfo");
                sucCount += 1;
            }
            catch (Exception ex)
            {
                ComLib.LogLib.Log4NetBase.Log(ex.Message);
                JscriptMsg("下载时发生错误请联系管理员！", searchURL, "Error");
            }
            //记录日志
            AddAdminLog(DTEnums.ActionEnum.Export.ToString(), "导出NC用户信息" + sucCount + "条，失败" + errorCount + "条");

            JscriptMsg("下载成功" + sucCount + "条，失败" + errorCount + "条！", searchURL, "Success");
        }

        protected void ConfigExportValidate(ExcelExportProvider provider, DataSet container, string typeName)
        {
            ///验证数据容器中是否存在DataTable
            if (container.Tables.Count == 0) throw new Exception("DataSet对象容器中没有任何DataTable对象!");
            ///验证导入配置中的配置节是否存在
            if (provider == null) throw new Exception(string.Format("配置中不存在类型为:{0}的导入配置项!", typeName));
            ///验证配置节中是否包含至少1个worksheet
            if (provider.Worksheets == null || provider.Worksheets.Count == 0) throw new Exception(string.Format("配置中类型为:{0}的配置节中不包含Worksheet的定义", typeName));
            // 验证数据容器中存在配置节中配置的datatable
            foreach (var worksheet in provider.Worksheets)
            {
                foreach (Area area in worksheet.Areas)
                    if (!container.Tables.Contains(area.DataTable))
                        throw new Exception(string.Format("DataTable中不包含表 {0}", area.DataTable));
            }
        }

        #endregion

        #region 导出二维码图片
        /// <summary>
        /// 导出二维码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void exportIMG_Click(object sender, EventArgs e)
        {
            var nclist = ext_ncuserService.Instance.Get_AllData_List();
            nclist.ForEach(o =>
            {
                var entity = qr_QrCodeRelateService.Instance.Get_SingleEntity_byWhere(
                    qr_QrCodeRelate._.qr_Type == 1 && qr_QrCodeRelate._.IsDelete == false
                    && qr_QrCodeRelate._.rel_Code == o.nc_code);
                if (entity != null)
                {
                    WebClient my = new WebClient();

                    var qrcode = qr_QrCodeService.Instance.Get_SingleEntity_byWhere(qr_QrCode._.id == entity.qr_CodeID);
                    if (qrcode != null)
                    {
                        try
                        {
                            byte[] mybyte;
                            mybyte = my.DownloadData(qrcode.qrcode_url);
                            MemoryStream ms = new MemoryStream(mybyte);
                            System.Drawing.Image img;
                            img = System.Drawing.Image.FromStream(ms);
                            var path = System.Web.HttpContext.Current.Request.MapPath("/upload/qrcodeimg/");
                            img.Save(path
                                + o.nc_code + "-"
                                + o.name.Replace("?", "").Replace("？", "").Replace("<", "").Replace(">", "") + ".png",
                                ImageFormat.Png);   //保存
                            //下面直接输出
                            //Response.ClearContent();
                            //Response.ContentType = "image/gif";
                            //Response.BinaryWrite(mybyte);
                        }
                        catch (Exception ex)
                        {
                            ComLib.LogLib.Log4NetBase.Log(o.nc_code + "错误" + ex.Message);
                        }
                    }
                }
            });
        }
        #endregion

        #region 检验
        /// <summary>
        /// 检验二维码准确性，只用于检验蓝甄二维码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btncheck_Click(object sender, EventArgs e)
        {
            ComLib.LogLib.Log4NetBase.Log("---------------开始检查NC！");
            try
            {
                DbSession.Default.FromSql("DELETE qr_check where qrtype=88").Execute();

                DataTable table = new DataTable();
                string sql = @"SELECT nc.nc_code,qr.scene_id,qr.qrcode_url,qr.code_url,qr.wx_title,qr.wx_content,qr.wx_imgurl,qr.wx_url
from ext_ncuser nc left join qr_QrCodeRelate rel on nc.nc_code=rel.rel_Code 
left join qr_QrCode qr on rel.qr_Scene_ID=qr.scene_id where rel.IsDelete=0";

                table = DbSession.Default.FromSql(sql).ToTable();
                table.TableName = "checktb";

                CheckQrcode check = new CheckQrcode();
                Qrcode_vigo vigo = new Qrcode_vigo("http://my.erpcoo.com/index.php/Api/Qrcode/index", "sdf5sf5et5e42t5");

                for (int i = 0; i < table.Rows.Count; i++)
                {
                    try
                    {
                        #region check

                        var imgurl = table.Rows[i]["qrcode_url"].ToString();
                        var qrcodecontent = check.getqrcontent(imgurl);
                        var resultwx = vigo.GetWXContent("", table.Rows[i]["scene_id"].ToString());

                        var vigomessage0 = "title:" + resultwx.message[0].title
                            + "desc:" + resultwx.message[0].shortdesc
                            + "pic:" + resultwx.message[0].picurl
                            + "link:" + resultwx.message[0].linkurl;
                        var message0 = "title:美赞臣蓝臻，突破性贴近宝宝需求，新妈买一赠一限量臻享"
                                + "desc:"
                                + "pic:http://qrcode.mjn.howjoin.com/imgforweixin/ac419.jpg"
                                + "link:" + "http://wx.ismartgo.com/app/lighthouse/index.aspx?from=" 
                                + table.Rows[i]["nc_code"].ToString() + "$type=1$openid=####";
                        var vigomessage1 = "title:" + resultwx.message[1].title
                            + "desc:" + resultwx.message[1].shortdesc
                            + "pic:" + resultwx.message[1].picurl
                            + "link:" + resultwx.message[1].linkurl;
                        var message1 = "title:马上加入美赞臣A＋妈妈会，尊享360°孕育礼遇"
                                + "desc:一键注册，终身礼遇"
                                + "pic:http://admin.mjn.howjoin.com/images/p4.jpg"
                                + "link:" + "http://svr.meadjohnson.com.cn/mjnwx/client_phone.action?regSubChannel=188$NCCode="
                                    + table.Rows[i]["nc_code"].ToString() + "$openId=####";
                        var vigomessage2 = "title:" + resultwx.message[2].title
                                + "desc:" + resultwx.message[2].shortdesc
                                + "pic:" + resultwx.message[2].picurl
                                + "link:" + resultwx.message[2].linkurl;
                        var message2 = "title:不可错过的海量专业孕育课程＆胎教早教资源！"
                                + "desc:有声资源每周更新，满足妈妈＆宝宝共同需求"
                                + "pic:http://admin.mjn.howjoin.com/images/p2.jpg"
                                + "link:" + "http://mp.weixin.qq.com/s?__biz=MjM5MjM1NjMzNA==$mid=2656105052$idx=2$sn=0d2328393e16964b17e11e30bb85378f$scene=1$srcid=06209qW7BXxURv3bBLvzMGHZ";
                        var vigomessage3 = "title:" + resultwx.message[3].title
                                + "desc:" + resultwx.message[3].shortdesc
                                + "pic:" + resultwx.message[3].picurl
                                + "link:" + resultwx.message[3].linkurl;
                        var message3 = "title:【会员福利】奶粉、京东优惠券、巧虎礼包、滴滴红包等你拿,还有……"
                                + "desc:惊喜连连，准备好了么？"
                                + "pic:http://admin.mjn.howjoin.com/images/p3.jpg"
                                + "link:" + "http://mp.weixin.qq.com/s?__biz=MjM5MjM1NjMzNA==$mid=2656105052$idx=3$sn=8478a978359403d68c1452f132455d32$scene=1$srcid=0620AZL0kIEOrjKTGX6Y2emW";
                    

                        qr_Check qrc = new qr_Check()
                        {
                            qrtype = "88",
                            rel_code = table.Rows[i]["nc_code"].ToString(),
                            scene_id = table.Rows[i]["scene_id"].ToString(),

                            code_url = table.Rows[i]["code_url"].ToString(),
                            httpcode_url = qrcodecontent,
                            iseqccode_url = (table.Rows[i]["code_url"].ToString() == qrcodecontent),

                            

                            message1 = message0,
                            vigomessage1 = vigomessage0,
                            iseq1 = (message0 == vigomessage0),

                            message2 = message1,
                            vigomessage2 = vigomessage1,
                            iseq2 = (message1 == vigomessage1),

                            message3 = message2,
                            vigomessage3 = vigomessage2,
                            iseq3 = (message2 == vigomessage2),

                            message4=message3,
                            vigomessage4 = vigomessage3,
                            iseq4 = (message3 == vigomessage3)
                        };
                        qr_CheckService.Instance.Add_Entity(qrc);

                        #endregion

                    }
                    catch(Exception ex)
                    {
                        ComLib.LogLib.Log4NetBase.Log(table.Rows[i]["nc_code"].ToString() + "检查NC错误:" + ex.Message);
                    }
                }
            }
            catch (Exception ex)
            {
                ComLib.LogLib.Log4NetBase.Log("检查NC错误:" + ex.Message);
            }
        }
        #endregion
    }
}